package br.edu.ufabc.gtrnp.helppo.presentation.filter;

import static br.edu.ufabc.gtrnp.helppo.util.HelppoConstants.USUARIO_LOGADO;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import br.edu.ufabc.gtrnp.helppo.persistence.entity.Usuario;


public class UsuarioAutenticadoRequestFilter implements Filter {
	private static String login;

	@Override
	public void destroy() {
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest httpRequest = (HttpServletRequest)request;
		
		Usuario usuario = (Usuario) httpRequest.getSession().getAttribute(USUARIO_LOGADO);
		
		if(!(httpRequest.getRequestURI().contains("home.do")||
				httpRequest.getRequestURI().contains("login.do")||
				httpRequest.getRequestURI().contains("tutoriais.do")||
				httpRequest.getRequestURI().contains("quemSomos.do")||
				httpRequest.getRequestURI().contains("cadastroUsuario.do"))&& usuario == null){
			RequestDispatcher rd = httpRequest.getRequestDispatcher(login);
			rd.forward(httpRequest, response);
			return;
		}
		chain.doFilter(httpRequest, response);

	}

	@Override
	public void init(FilterConfig config) throws ServletException {
		login = config.getInitParameter("LOGIN_PAGE");
	}

}
